const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");

const backgroundImg = new Image();

let lastTime = 0;
let fps = 0;
let backgroundOffset = 0;
const OFFSET_VELOCITY = 130;

function erase() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}

function draw() {
    ctx.save();
    backgroundOffset =
        backgroundOffset < canvas.width
            ? backgroundOffset + OFFSET_VELOCITY / fps
            : 0;
    ctx.save();
    ctx.translate(-backgroundOffset, 0);
    ctx.drawImage(backgroundImg, 0, 0);
    ctx.drawImage(backgroundImg, backgroundImg.width - 2, 0);

    ctx.restore();
}

function calculateFps(now) {
    let fps = 1000 / (now - lastTime);
    lastTime = now;
    return fps;
}

function animate(now) {
    if (now === undefined) {
        now = +new Date();
    }

    fps = calculateFps(now);

    erase();
    draw();

    requestAnimationFrame(animate);
}
backgroundImg.src = "./pic.png";
backgroundImg.onload = () => {
    draw();
};
requestAnimationFrame(animate);
